package com.tn.exam.util.taoyf.enchar;
import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5 瀹搞儱鍙跨猾锟� * @author Black.zhu
 * @date 2012-3-24
 */
public class MD5 {

	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	private static String byteArrayToHexString(byte[] b) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			buf.append(byteToHexString(b[i]));
		}
		return buf.toString();
	}

	private static String byteToHexString(byte b) {

		return hexDigits[(b & 0xf0) >> 4] + hexDigits[b & 0x0f];
	}

	public static String MD5Encode(String origin) {
		String resultString = null;

		resultString = new String(origin);
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(resultString
					.getBytes()));
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return resultString;
	}

	public static void main(String[] args) {
		if (Array.getLength(args) == 0) { 
			System.out.println("MD5 Test suite:");
			System.out.println("MD5(\"\"):" + MD5.MD5Encode("123456"));
			System.out.println("MD5(\"a\"):" + MD5.MD5Encode("a"));
			System.out.println("MD5(\"abc\"):" + MD5.MD5Encode("abc"));
			System.out.println("MD5(\"message digest\"):"
					+ MD5.MD5Encode("message digest"));
			System.out.println("MD5(\"abcdefghijklmnopqrstuvwxyz\"):"
					+ MD5.MD5Encode("abcdefghijklmnopqrstuvwxyz"));
			System.out
					.println("MD5(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"):"
							+ MD5
									.MD5Encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"));
		} else
			System.out
					.println("MD5(" + args[0] + ")=" + MD5.MD5Encode(args[0]));

	}
}
